package com.xiaolei.fastnio.library.Protocol.Impls

import com.xiaolei.fastnio.library.Client.Session
import com.xiaolei.fastnio.library.Protocol.IProtocol
import java.util.*

/**
 * 将数据转换成字符串，但是断行标示是 \n 换行符
 */
class ScalarsProtocol : IProtocol<String>
{
    private val datas = LinkedList<Byte>()
    private val splitChar = '\n'.toByte()

    override fun decode(session: Session, byteArray: ByteArray, len: Int): String?
    {
        for (i in 0 until len)
        {
            datas.add(byteArray[i])
        }
        val index = datas.indexOf(splitChar)
        return if (index == -1)
        {
            null
        } else
        {
            val data = ByteArray(index)
            for (i in 0 until index)
            {
                data[i] = datas.remove()
            }
            datas.remove()
            String(data)
        }
    }
    override fun onClear()
    {
        datas.clear()
    }
}